#!/usr/bin/python3
# -*- coding:utf-8 -*-
# __author__ == taoyulong2018@gmail.com
# __time__ == 2023/6/29 18:44
# ===========================================
#       题目名称： 57. 插入区间
#       题目地址： https://leetcode.cn/problems/insert-interval/
#       题目描述： https://note.youdao.com/s/LWYgPSzT
# ===========================================


class Solution:
    """
        给你一个 无重叠的 ，按照区间起始端点排序的区间列表。
    在列表中插入一个新的区间，你需要确保列表中的区间仍然有序且不重叠（如果有必要的话，可以合并区间）。
    """

    def insert(self, intervals, newInterval):
        merged = []
        intervals.append(newInterval)
        # 排序
        intervals.sort(key=lambda x: x[0])
        for interval in intervals:
            if not merged or interval[0] > merged[-1][1]:
                merged.append(interval)
            else:
                merged[-1][1] = max(merged[-1][1], interval[1])
        return merged


if __name__ == '__main__':
    s = Solution()
    # [[1,5],[6,9]]
    print("intervals = [[1,3],[6,9]], newInterval = [2,5] => ", s.insert(intervals=[[1, 3], [6, 9]], newInterval=[2, 5]))
    # intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
    print("intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] => ", s.insert(intervals=[[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], newInterval=[4, 8]))
